<template>
  <el-container style="padding: 15px">
    <el-header height="120px">
      <el-form size="small" label-width="70px">
        <el-row type="flex" :gutter="20" align="middle">
          <el-col :span="4">
            <el-form-item label="项目编号">
              <el-input v-model="searchObj.reportId" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="项目名称">
              <el-input v-model="searchObj.reportName" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="审核阶段">
              <el-select v-model="searchObj.leafId">
                <el-option v-for="item in leafList" :key="item.id" :value="item.id" :label="item.leafName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="报告类型">
              <el-select v-model="searchObj.reportTypeId">
                <el-option :value="2" label="正评" />
                <el-option :value="1" label="预评" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="估价目的">
              <el-select v-model="searchObj.reportObjectiveId">
                <el-option v-for="item in objectiveList" :key="item.id" :value="item.id" :label="item.reportObjectiveName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" align="middle" :gutter="20">
          <el-col :span="3">
            <el-form-item label="出具日期">
              <el-date-picker
                v-model="searchObj.startTime"
                value-format="timestamp"
                type="date"
                placeholder="开始时间"
                @change="startTimeChangeHandler"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label=" ">
              <el-date-picker
                v-model="searchObj.endTime"
                value-format="timestamp"
                type="date"
                placeholder="结束时间"
                @change="EndTimeChangeHandler"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="不动产类型" label-width="85px">
              <el-select v-model="searchObj.projectId">
                <el-option v-for="item in projectList" :key="item.id" :value="item.id" :label="item.projectName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="客户全称">
              <el-input v-model="searchObj.channelName" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="业务人员">
              <el-select v-model="searchObj.businessUserId" style="width: 100%" clearable filterable>
                <el-option v-for="item in noPageReportUserList" :key="item.id" :value="item.id" :label="item.nickName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" align="center" justify="center">
          <el-col :span="4">
            <el-button type="primary" size="small" @click="getReportList">搜索</el-button>
            <el-button size="small" @click="clearSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-header>
    <el-divider />
    <el-main>
      <el-form size="small">
        <el-row type="flex">
          <el-col :span="4">
            <el-form-item>
              <el-button v-if="hasRole(['admin', 'valuer'])" type="primary" :loading="downloadingButtonLoding" @click="download">估价师下载我的表单</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button v-if="hasRole(['admin', 'business'])" type="primary" :loading="downloadingButtonBusiness" @click="downloadBusiness">业务员下载我的表单</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="reportList">
        <el-table-column label="项目编号" prop="reportId" width="120px">
          <template v-slot="scope">
            <el-button type="text" size="small" @click="toDetails(scope.row.id)">{{ scope.row.reportId }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" prop="reportName" width="300px" :formatter="subName" />
        <el-table-column label="项目状态" prop="leafName" />
        <el-table-column label="报告类型" prop="reportTypeName" />
        <el-table-column label="估价目的" prop="reportObjectiveName" />
        <el-table-column label="操作" fixed="right">
          <template v-slot="scope">
            <el-dropdown size="small">
              <el-button type="primary" size="small">
                <i class="el-icon-s-tools" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button type="text" size="small" @click="pushAuditReport(scope.row)">提交审核</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="text" size="small">出具</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="text" size="small">用印申请</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="text" size="small" @click="fileAuditReport(scope.row)">归档</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="text" size="small">作废</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="text" size="small">转正</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 40, 80]"
        :page-size="sizePage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-main>
  </el-container>
</template>

<script>
import {
  downloadStatisticsBusiness,
  getMyReportList,
  getReportObjectiveNoPage,
  getReportProjectNoPage,
  myReportListSearch
} from '@/api/report'
import { mapGetters } from 'vuex'
import { validObj } from '@/utils/validate'
import { auditToFile, getAuditStatusNoPage, submitAudit } from '@/api/flow'
import { ellipsisString } from '@/utils'
import { downloadStatistics } from '@/api/report'
import { noPageUser } from '@/api/user'

export default {
  name: 'Index',

  data() {
    return {
      reportList: [],
      noPageReportUserList: [],
      projectList: [],

      currentPage: 1,
      sizePage: 10,
      totalPage: 0,

      searchObj: {},

      leafList: [],
      objectiveList: [],

      downloadingButtonLoding: false,
      downloadingButtonBusiness: false
    }
  },

  computed: {
    ...mapGetters([
      'id',
      'roles'
    ])
  },

  created() {
    this.init()
  },

  methods: {

    init() {
      this.getReportList()
      this.getSearchFormList()
      this.getNoPageUserList()
      this.getNoPageProject()
    },

    download() {
      const searchObj = this.searchObj
      this.downloadingButtonLoding = true
      downloadStatistics(searchObj, this.id).then(res => {
        const url = window.URL.createObjectURL(new Blob([res]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '估价师-我的表单.xlsx')
        document.body.appendChild(link)
        link.click()
        this.downloadingButtonLoding = false
      }).finally(() => {
        this.downloadingButtonLoding = false
      })
    },
    downloadBusiness() {
      const searchObj = this.searchObj
      this.downloadingButtonBusiness = true
      downloadStatisticsBusiness(searchObj, this.id).then(res => {
        const url = window.URL.createObjectURL(new Blob([res]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '业务员-我的表单.xlsx')
        document.body.appendChild(link)
        link.click()
        this.downloadingButtonBusiness = false
      }).finally(() => {
        this.downloadingButtonBusiness = false
      })
    },

    getReportList() {
      const currentPage = this.currentPage
      const sizePage = this.sizePage
      const searchObj = this.searchObj
      if (validObj(searchObj)) {
        // 搜索
        myReportListSearch(this.id, currentPage, sizePage, searchObj).then(res => {
          console.log(res)
          this.reportList = res.data.list
          this.totalPage = res.data.total
        })
      } else {
        getMyReportList(this.id, currentPage, sizePage).then(res => {
          console.log(res)
          this.reportList = res.data.list
          this.totalPage = res.data.total
        })
      }
    },

    getNoPageUserList() {
      noPageUser().then(res => {
        this.noPageReportUserList = res.data.users
      })
    },
    getNoPageProject() {
      getReportProjectNoPage().then(res => {
        this.projectList = res.data.list
      })
    },

    startTimeChangeHandler(val) {
      this.reportCommonObj.startTime = val
    },
    EndTimeChangeHandler(val) {
      this.reportCommonObj.endTime = val
    },

    handleSizeChange(val) {
      this.sizePage = val
      this.getReportList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getReportList()
    },

    toDetails(id) {
      this.$router.push({ path: '/report/details', query: { id: id }})
    },

    clearSearch() {
      this.searchObj = {}
      this.getReportList()
      // 重置成功提示框
      this.$message({
        message: '重置成功',
        type: 'success'
      })
    },

    async getSearchFormList() {
      await getAuditStatusNoPage().then(res => {
        this.leafList = res.data.list
      })
      await getReportObjectiveNoPage().then(res => {
        this.objectiveList = res.data.list
      })
    },

    pushAuditReport(data) {
      const reportId = data.id
      const id = this.id
      this.$confirm('确认提交后将!!!不会!!!自动保存当前报告信息，并且文本信息将不可更改（附件文件可正常上传下载），直到审核阶段完成，确定提交当前的报告信息吗？', '提交审核', {
        confirmButtonText: '提交',
        cancelButtonText: '取消'
      }).then(() => {
        submitAudit(reportId, id).then(res => {
          this.$message.success(res.message)
          this.getReportList()
        })
      })
    },

    fileAuditReport(data) {
      const reportId = data.id
      const leafId = data.leafId
      const id = this.id
      const auditData = {
        reportId: reportId,
        leafId: leafId,
        auditUserId: id
      }
      this.$confirm('此操作将改变当前状态，并且自动生成审核记录，确认继续吗？', '归档申请', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        auditToFile(auditData).then(res => {
          this.$message.success(res.message)
        })
      })
    },

    subName(row, column, cellValue, index) {
      return ellipsisString(cellValue)
    },

    hasRole(role) {
      const roles = this.roles
      const filter = roles.filter(v => role.includes(v))
      return filter.length !== 0
    }
  }
}
</script>

<style scoped>

</style>
